<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SoundManager 2: Deferred loading / Lazy-loading / Dynamic script loading Example</title>
<meta name="description" content="How to load soundmanager2.js on-the-fly using JavaScript, and start it dynamically after window.load() has already fired using beginDelayedInit()." />
<style type="text/css">
#soundmanager-debug {
 /* SM2 debug container (optional, use or customize this as you like - makes in-browser debug output more useable) */
 position:fixed;_position:absolute;right:1em;bottom:1em;width:50em;height:18em;overflow:auto;background:#fff;margin:1em;padding:1em;border:1px solid #999;font-family:monaco,"lucida console",verdana,tahoma,"sans serif";font-size:x-small;line-height:1.5em;opacity:0.9;filter:alpha(opacity=90);
}
</style>
<!-- some CSS for this demo page, not required for SM2 -->
<link rel="stylesheet" href="template.css" />

<!-- SM2 BAREBONES TEMPLATE: START -->

<script type="text/javascript">

function loadScript(sURL, onLoad) {

  function loadScriptHandler() {
    var rs = this.readyState;
    if (rs == 'loaded' || rs == 'complete') {
      this.onreadystatechange = null;
      this.onload = null;
      if (onLoad) {
        onLoad();
      }
    }
  }

  function scriptOnload() {
    this.onreadystatechange = null;
    this.onload = null;
    window.setTimeout(onLoad,20);
  }

  var oS = document.createElement('script');

  oS.type = 'text/javascript';
  if (onLoad) {
    oS.onreadystatechange = loadScriptHandler;
    oS.onload = scriptOnload;
  }

  oS.src = sURL;
  document.getElementsByTagName('head')[0].appendChild(oS);

}

function msg(s) {

  document.getElementById('sm2-status').innerHTML += '<br />' + s;

}

window.onload = function() {

  msg('Window loaded, waiting 1 second...');

  setTimeout(function() {

    msg('Loading soundmanager2.js...');

    loadScript('../../script/soundmanager2.js', function() {

      // SM2 script has loaded

      window.setTimeout(function() {
        msg('soundmanager2.js loaded, delaying before setup()...');
      }, 500);

      window.setTimeout(function() {

        soundManager.setup({

          url: '../../swf/',

          onready: function() {

            soundManager.createSound({
              id:'foo',
              url:'../_mp3/mouseover.mp3'
            }).play();

            msg('Started OK');

          },

          ontimeout: function() {

            msg('Loaded OK, but unable to start: unsupported/flash blocked, etc.');

          }

        });

        // ensure start-up in case document.readyState and/or DOMContentLoaded are unavailable
        soundManager.beginDelayedInit();

      }, 1000);

    });

  },1000);

}

</script>
</head>

<body style="height:100%">

<div style="margin-right:43em">

 <h1>SoundManager 2: Lazy Loading Example</h1>
 <p>This is an example of dynamically loading SoundManager 2 using JS, after <code>window.onload()</code> has fired.</p>

 <h2>How it works</h2>
 <p>This page waits until <code>window.onload()</code>, delays 1 second and loads soundmanager2.js, which should then start up.</p>
 <p><b>Behaviour note:</b> SM2 will not automatically start if it is loaded at or after the <code>DOMContentLoaded</code> event has fired, which may be common with most JS loaders.</p>
 <p>However, SM2 will try to start once <code>soundManager.setup()</code> is called and a <code>url</code> attribute has been provided.</p>
 <p>If you want to ensure that SM2 starts after setup, you can call <code>soundManager.beginDelayedInit()</code> - this should be safe to call after <code>DOMContentLoaded</code> has fired.</p>

<h2>Pseudo-code Example</h2>

<p>Once SM2 has been dymamically loaded, you can call its <code>setup()</code> method. Passing a <code>url</code> attribute will trigger the initialization process.</p>

<pre class="block"><code>loadJS('<span>soundmanager2.js</span>', function() {
  soundManager.setup({
    url: '<span>/path/to/swfs/</span>',
    onready: function() {
      <span><span>// good to go!</span></span>
      <span><span>// soundManager.createSound(...), etc.</span></span>
    }
  });
});</code></pre>

<h2>Live Example</h2>

<p>SoundManager 2 status: <b id="sm2-status">Waiting for window.onload()...</b></p>

<pre class="block"><code><span><span>/**
 * Dynamic script loading helper (example)
 * Normalizes good browser onload() vs. IE readyState weirdness
 */
</span></span>
function loadScript(sURL, onLoad) {

  function loadScriptHandler() {
    var rs = this.readyState;
    if (rs == '<span>loaded</span>' || rs == '<span>complete</span>') {
      this.onreadystatechange = null;
      this.onload = null;
      if (onLoad) {
        onLoad();
      }
    }
  }

  function scriptOnload() {
    this.onreadystatechange = null;
    this.onload = null;
    window.setTimeout(onLoad,20);
  }

  var oS = document.createElement('<span>script</span>');
  oS.type = '<span>text/javascript</span>';
  if (onLoad) {
    oS.onreadystatechange = loadScriptHandler;
    oS.onload = scriptOnload;
  }
  oS.src = sURL;
  document.getElementsByTagName('<span>head</span>')[0].appendChild(oS);

}

<span><span>// Wait for window load, then load soundmanager2.js, let it start and play a test sound</span></span>

window.onload = function() {</span>

  msg('<span>Window loaded, waiting 1 second...</span>');

  setTimeout(function() {

    msg('<span>Loading soundmanager2.js...</span>');

    loadScript('<span>../../script/soundmanager2.js</span>', function() {

      <span><span>// SM2 script has loaded</span></span>

      window.setTimeout(function() {
        msg('<span>soundmanager2.js loaded, delaying before setup()...</span>');
      }, 500);

      window.setTimeout(function() {

        soundManager.setup({
          url: '<span>../../swf/</span>',
          onready: function() {
            soundManager.createSound({
              id: '<span>foo</span>',
              url: '<span>../_mp3/mouseover.mp3</span>'
            }).play();
            msg('<span>Started OK</span>');
          },
          ontimeout: function() {
            msg('<span>Loaded OK, but unable to start: unsupported/flash blocked, etc.</span>');
          }
        });

        <span><span>// ensure start-up in case document.readyState and/or DOMContentLoaded are unavailable</span></span>
        soundManager.beginDelayedInit();

      }, 1000);

    });

  }, 1000);

</span>}
</code></pre>

 <h2 id="flashblock-handling">Handling flash blockers</h2>
 <p>It's good to let users see the flash component of SM2, so those with flash blockers can unblock it and allow SM2 to start. For more info on this, see the <a href="../flashblock/" title="SoundManager 2 with Flash block handling" onclick="if (!document.domain && !this.href.match(/index/i)) this.href=this.href+'index.html'">Flashblock</a> example.</p>

 <h2 style="margin-top:1em">Preventing auto-init using SM2_DEFER</h2>
 <p>If you want to completely defer the normal start-up of SM2 and call the SoundManager() constructor yourself, you can declare an SM2_DEFER global and set it to true. See the <a href="sm2_defer-example.html" title="SoundManager 2: SM2_DEFER example">SM2_DEFER example</a> for details.</p>

 <h2 style="margin-top:1em">Disabling debug output</h2>
 <p>SoundManager 2 will write to a debug &lt;div&gt; element or a javascript console if available, by default. To disable it, simply set the relevant property to false:</p>
<code>soundManager.setup({ debugMode: false });</code>
 <p>To see related configuration code, refer to the source of this page which basically does all of the above "for real."</p>
 <h2>Troubleshooting</h2>
 <p>If SM2 is failing to start and throwing errors due to flash security, timeouts or other issues, check out the <a href="../../doc/getstarted/#troubleshooting" title="SoundManager 2 troubleshooting tool" onclick="if (!document.domain && !this.href.match(/index/i)) this.href=this.href.replace(/\#/,'index.html#')">troubleshooting tool</a> which can help you fix things.</p>
 <h2>No-debug, compressed version of soundmanager2.js</h2>
 <p>You can also use the "minified" (60% smaller) version of SM2, which has debug output and comments removed for you: <a href="../../script/soundmanager2-nodebug-jsmin.js">soundmanager2-nodebug-jsmin.js</a>. If you can, serve this with gzip compression for even greater bandwidth savings!</p>
 
</div>

</body>
</html>
